import express from 'express'
import { Response, Request } from "express"

const router = express.Router()

import { success, failure } from '../utils/responses'
import { Article } from "../entities/Article"
import { AppDataSource } from "../config/database"
import { FindManyOptions, Like } from "typeorm";

/**
 * 根据搜索文本搜索列表
 */
router.get('/', async function (req: Request, res: Response) {
  try {
    const query = req.query

    const searchText = query.searchText // 搜索文本
    const currentPage = Math.abs(Number(query.currentPage)) || 1 // 当前页
    const pageSize = Math.abs(Number(query.pageSize)) || 10 // 每页条数
    const offset = (currentPage - 1) * pageSize // 偏移量

    const articleRepository = AppDataSource.getRepository(Article)

    const findOptions: FindManyOptions = {
      relations: {
        category: true,
        author: true,
        video: true
      },
      where: {
        title: Like(`%${searchText}%`)
      },
      order: {
        updatedAt: "DESC"
      },
      skip: offset,
      take: pageSize
    }

    const [articles, totalCount] = await articleRepository.findAndCount(findOptions)

    // 去除不需要的字段
    const filterArticles = articles.map(article => {
      const { id, title, category, coverImages, video, author, updatedAt } = article;
      return {
        id,
        title,
        coverImages,
        video,
        updatedAt,
        category: {
          id: category.id,
          name: category.name,
        },
        author: {
          id: author.id,
          username: author.username,
        }
      }
    })

    success(res, '查询文章列表成功', {
      articles: filterArticles,
      pagination: {
        totalPage: Math.ceil(totalCount / pageSize),
        currentPage,
        pageSize,
        totalCount
      }
    })
  } catch (error) {
    failure(res, error)
  }
})

export default router
